package com.youlu.campus.admin.task;

import cn.hutool.core.util.RandomUtil;
import com.youlu.campus.admin.community.service.ActivityService;
import com.youlu.campus.common.utils.RedisKeyUtil;
import com.youlu.campus.entity.ActivityInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 活动相关任务
 *
 * @Description: ActivityInfoTask
 * @Date 2025/7/17
 * @module ActivityInfoTask
 * @author: su
 */
@Slf4j
@Component
public class ActivityInfoTask {


    @Autowired
    private ActivityService activityService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 每小时 随机生成数字 报名数
     */
    @Scheduled(fixedDelay = 60 * 60 * 1000)
    public void randomNumActivity() {
        // 生成唯一的锁值（可以使用UUID）
        String lockValue = UUID.randomUUID().toString();
        String lockKey = RedisKeyUtil.getTaskActivityRandomNumLock();
        try {
            Boolean locked = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, 5, TimeUnit.MINUTES);
            log.info("randomNumActivity 活动列表 随机报名数增加  lockKey:{},lockValue:{},locked:{}", lockKey, lockValue, locked);
            if (locked) {
                log.info("randomNumActivity 获取到锁", lockKey, lockValue, locked);
                List<ActivityInfo> activeActivities = activityService.findActiveActivities();
                for (ActivityInfo activeActivity : activeActivities) {
                    Long randomEndJoinNum = activeActivity.getRandomEndJoinNum();
                    Long randomStartJoinNum = activeActivity.getRandomStartJoinNum();
                    if (randomStartJoinNum == 0 && randomEndJoinNum == 0) {
                        continue;
                    }
                    long activityRandomNum = randomStartJoinNum;
                    if (!randomStartJoinNum.equals(randomEndJoinNum)) {
                        activityRandomNum = RandomUtil.randomLong(activeActivity.getRandomStartJoinNum(), activeActivity.getRandomEndJoinNum());
                    }
                    long newRandomInitJoinNum = activeActivity.getRandomInitJoinNum() + activityRandomNum;
                    //不批量该 避免 批量修改错误
                    activityService.updateRandomInitJoinNum(activeActivity.getId(), newRandomInitJoinNum);
                }
            } else {
                log.info("randomNumActivity 获取锁失败,其他服务正在执行");
            }
        } finally {
            // 确保锁是当前服务获取的，才释放锁（防止释放其他服务的锁）
            if (lockValue.equals(redisTemplate.opsForValue().get(lockKey))) {
                redisTemplate.delete(lockKey);
                log.info("randomNumActivity 释放锁");
            }
        }
    }
}
